package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.*;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.converter.ProductConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.entitys.ItemDesc;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.ItemDescMapper;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.AllProductRequest;
import com.cskaoyan.shopping.dto.AllProductResponse;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.dto.RecommendResponse;
import com.cskaoyan.shopping.service.ICartService;
import com.cskaoyan.shopping.service.IProductService;
import com.cskaoyan.shopping.utils.ExceptionProcessorUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 创建日期: 2022/04/24 15:52
 *
 * @author ChengWenqi
 */
@Service
@Slf4j
public class IProductServiceImpl implements IProductService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;

    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse response = new ProductDetailResponse();

        try {
            // 参数校验
            request.requestCheck();
            // 取出商品id
            Long productId = request.getId();
            // 查找 item 表，获取商品详情
            Example example = new Example(Item.class);
            example.createCriteria()
                    .andEqualTo("status", GlobalConstants.ITEM_STATUS_NORMAL)
                    .andEqualTo("id", productId);
            List<Item> items = itemMapper.selectByExample(example);

            ProductDetailDto productDetailDto = new ProductDetailDto();
            if (!CollectionUtils.isEmpty(items) && items.size() == 1) {
                productDetailDto = productConverter.item2DetailDto(items.get(0));
                // 查找 item_desc 表，获取商品 detail
                ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(productId);
                if (itemDesc != null) {
                    productDetailDto.setDetail(itemDesc.getItemDesc());
                }
            }
            response.setProductDetailDto(productDetailDto);
            // 设置成功响应码和响应信息
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("IProductServiceImpl.getProductDetail occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        AllProductResponse response = new AllProductResponse();
        log.info(request.toString());
        try {
            // 参数校验
            request.requestCheck();
            //开启分页
            Integer page = request.getPage();
            Integer size = request.getSize();
            PageHelper.startPage(page, size);
            //条件查询
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            if (request.getSort() != null && !"".equals(request.getSort())) {
                example.setOrderByClause(request.getSort());
            }else {
                example.setOrderByClause(GlobalConstants.ALL_PRODUCT_DEFAULT_SORT);
            }
            if (request.getCid() != null) {
                criteria.andEqualTo("cid",request.getCid());
            }
            if (request.getPriceGt() != null) {
                criteria.andGreaterThan("price", request.getPriceGt());
            }
            if (request.getPriceLte() != null) {
                criteria.andLessThan("price", request.getPriceLte());
            }
            criteria.andEqualTo("status", GlobalConstants.ITEM_STATUS_NORMAL);
            // 查询
            List<Item> items = itemMapper.selectByExample(example);
            List<ProductDto> productDtos = new ArrayList<>();
            if (!CollectionUtils.isEmpty(items)) {
                productDtos = productConverter.items2Dto(items);
            }
            //统计获取到的数据条数
            PageInfo<Item> pageInfo = new PageInfo<>(items);
            //封装返回信息
            response.setTotal(pageInfo.getTotal());
            response.setData(productDtos);
            // 设置成功响应码和响应信息
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("IProductServiceImpl.getAllProduct occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    @Override
    public RecommendResponse getRecommendGoods() {
        RecommendResponse response = new RecommendResponse();

        try {
            // 根据推荐商品版块的panelId，查找panel详细信息及对应的商品id
            Panel panel = panelMapper.selectByPrimaryKey(GlobalConstants.RECOMMEND_PANEL_ID);
            if (panel == null) {
                throw new BizException(ShoppingRetCode.DB_EXCEPTION.getCode(), ShoppingRetCode.DB_EXCEPTION.getMessage());
            }
            // 根据panelId，查找 panelContent 和对应的商品信息
            List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(GlobalConstants.RECOMMEND_PANEL_ID);

            PanelDto panelDto = contentConverter.panel2Dto(panel);
            panelDto.setPanelContentItems(contentConverter.panelContentItem2Dto(panelContentItems));

            Set<PanelDto> panelDtos = new LinkedHashSet<>();
            panelDtos.add(panelDto);
            response.setPanelContentItemDtos(panelDtos);
            // 设置成功响应码和响应信息
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (BizException e) {
            log.error("IProductServiceImpl.getAllProduct occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }


}
